import json
from django.views import View
from django.http import JsonResponse, request
from django_redis import get_redis_connection

# 登录注册
import re

from libs.qiniuyun.qiniu_upload import upload_img
from .models import User
from django.contrib.auth import login,logout
from django.contrib.auth import authenticate




class RegisterView(View):
    '''注册'''
    def get(self,request):

        # dict = json.loads(request.body)

        mobile = request.GET.get('mobile')

        # 短信验证码
        sms_code_client = request.GET.get('phonecode')

        # 密码
        password = request.GET.get('password')


        # password2 = request.GET.get('password')



        if not all([mobile,sms_code_client,password]):
            return JsonResponse({'errno':4103,'errmsg':'缺少必传参数'})


        if not re.match('^1[3-9]\d{9}$',mobile):
            return JsonResponse({'errno': 4500, 'errmsg': '手机号格式错误'})

        count = User.objects.filter(mobile=mobile).count()

        if count > 0:
            return JsonResponse({'errno':4003,'errmsg':'手机号重复注册'})


        if not re.match('^[a-zA-Z0-9]{8,20}$',password):
            return JsonResponse({'errno': 4106, 'errmsg': '密码格式错误'})

        # if password != password2:
        #     return JsonResponse({'errno':4106, 'errmsg':'两次输入的密码不一致'})

        redis_conn = get_redis_connection('verify_code')

        sms_code_server = redis_conn.get('sms_%s' %  mobile)

        if not sms_code_server:
            return JsonResponse({'errno':4002,'errmsg':'验证码过期'})

        if sms_code_client != sms_code_server.decode():
            return  JsonResponse({'errno':4004,'errmsg':'验证码有误'})

        try:
            # user = User.objects.create(password=password,mobile=mobile)
            user = User.objects.create_user(username = mobile,password=password,mobile=mobile)
        except Exception as e:
            return JsonResponse({'errno':4001,'errmsg':'保存到数据库出错'})

        login(request, user)

        response = JsonResponse({'errno':0,'errmsg':'注册成功'})

        response.set_cookie('username',user.username,max_age=3600 * 14 *24)

        return response


class LoginView(View):
    '''登录'''
    def post(self,request):
        dict = json.loads(request.body)

        mobile = dict.get('mobile')

        password =dict.get('password')

        if not all([mobile,password]):
            return JsonResponse({'errno':4103,'errmsg':'缺少必传参数'})

        # 验证是否能够登录
        user = authenticate(username=mobile,
                            password=password)


        if user is None:
            return JsonResponse({'errno':4105,'errmsg':'用户名或者密码错误'})


        login(request,user)

        response = JsonResponse({'errno': 0, 'errmsg': '登录成功'})

        response.set_cookie('username', user.username, max_age=3600 * 14 * 24)

        return response

    def get(self,request):
        user = request.user
        # print(request.META['REMOTE_ADDR'])

        if request.user.is_authenticated:
            name = request.user.username

            data = {"name": name,'user_id':1}
            return JsonResponse({ "errno": "0",
                                  "errmsg": "已登录",
                                  "data": data})
        else:
            return JsonResponse({"errno": "4101",
                                 "errmsg": "未登录"})


    def delete(self,request):

        logout(request)

        response = JsonResponse({ "errno": 0,"errmsg": "已登出"})

        response.delete_cookie('username')

        return response





# 个人中心
class UserCenter(View):

    def get(self, request):
        """返回用户信息"""
        if request.user.is_authenticated:
            try:
                user = User.objects.get(id=request.user.id)
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                     'errmsg': "DBERR"})

            # 拼接数据
            domain_name = 'http://qtsrimd9d.hn-bkt.clouddn.com/'
            print(user.avatar)  # 860505d7-4a22-436b-bad9-4c5325f85a10.png
            img_url = domain_name + str(user.avatar)

            data = {
                "avatar_url": img_url,
                "create_time": user.date_joined,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id
            }

            return JsonResponse({'data': data,
                                 "errno": "0",
                                 "errmsg": "OK",
                                 })

        else:
            # 用户未登录
            return JsonResponse({'errno': 4101,
                                 'errmsg': "SESSIONERR"})

    def post(self, request):
        """上传用户头像"""
        if request.user.is_authenticated:
            image_data = request.FILES.get('avatar')
            # print(request.FILES.get('avatar', None))
            image_path = '/home/ubuntu/Desktop/' + image_data.name
            img_key = upload_img(image_path)
            try:

                user = User.objects.filter(id=request.user.id).update(avatar=img_key)

                # 拼接数据
                domain_name = 'http://qtsrimd9d.hn-bkt.clouddn.com/'
                # print(type(domain_name + img_key))
                img_url = str(domain_name + img_key)
                # 返回更新后的数据
                data = {
                    "avatar_url": img_url
                }
                return JsonResponse({'data': data,
                                     "errno": "0",
                                     "errmsg": "头像上传成功",
                                     })
            except Exception as e:
                # 数据库查询错误
                return JsonResponse({'errno': 4001,
                                     'errmsg': "DBERR"})
        else:
            # 用户未登录
            return JsonResponse({'errno': 4101,
                                 'errmsg': "SESSIONERR"})

    def put(self, request):
        """修改用户名"""

        if request.user.is_authenticated:
            json_dict = json.loads(request.body)
            name = json_dict.get('name')


            try:
                User.objects.filter(id=request.user.id).update(username=name)
                return JsonResponse({
                    "errno": 0,
                    "errmsg": "修改用户名成功",
                })
            except Exception as e:
                # 数据库查询错误
                return JsonResponse({'errno': 4001,
                                     'errmsg': "DBERR"})
        else:
            # 用户未登录
            return JsonResponse({'errno': 4101,
                                 'errmsg': "SESSIONERR"})


# 用户实名认证
class UserAuthentication(View):
    def get(self, request):
        """用户实名认证"""
        if request.user.is_authenticated:
            try:
                user = User.objects.get(id=request.user.id)
                data = {
                    'real_name':user.real_name,
                    'id_card':user.id_card
                }
                return JsonResponse({
                    'data':data,
                    "errno": 0,
                    "errmsg": "认证信息发送成功",
                })

            except Exception as e:
                # 数据库查询错误
                return JsonResponse({'errno': 4001,
                                     'errmsg': "DBERR"})

        else:
            # 用户未登录
            return JsonResponse({'errno': 4101,
                                 'errmsg': "SESSIONERR"})







    def post(self, request):
        """用户实名认证"""

        if request.user.is_authenticated:
            json_dict = json.loads(request.body)
            real_name = json_dict.get('real_name')
            id_card = json_dict.get('id_card')

            # 信息校验
            if not all([real_name, id_card]):
                return JsonResponse({
                    'code': 4103,
                    'errmsg': '参数错误'
                })

            if not re.match(r'^[\u4e00-\u9fa5]{1,8}$', real_name):
                # 真名不合法
                return JsonResponse({
                    'code': 4103,
                    'errmsg': '参数错误'
                })
            # 身份证验证

            if not re.match(r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$', id_card):

                # 身份证不合法
                return JsonResponse({
                    'code': 4103,
                    'errmsg': '参数错误'
                })

            count = User.objects.filter(id_card=id_card).count()
            if count > 0:
                return JsonResponse({'errno': 4003, 'errmsg': '身份证号码重复'})

            # num = User.objects.filter(real_name=real_name).count()
            # if num > 0:
            #     return JsonResponse({'errno': 4003, 'errmsg': '姓名重复'})

            # 实名认证只能修改一次
            try:
                user = User.objects.get(id=request.user.id)
                # 如果真名和身份证存在，返回错误信息
                if user.real_name and user.id_card:
                    return JsonResponse({
                        'code': 4103,
                        'errmsg': '已实名认证'
                    })
                # 真名和身份证不存在，则保存在数据库
                else:
                    user = User.objects.filter(id=user.id).update(real_name=real_name,
                                               id_card=id_card)
                    return JsonResponse({
                        "errno": 0,
                        "errmsg": "认证信息保存成功",
                    })
            except Exception as e:
                # 数据库查询错误
                return JsonResponse({'errno': 4001,
                                     'errmsg': "DBERR"})

        else:
            # 用户未登录
            return JsonResponse({'errno': 4101,
                                 'errmsg': "SESSIONERR"})
